package com.huluobo.a2109mvpimdemo.login;

import android.content.Intent;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.huluobo.a2109mvpimdemo.IMApp;
import com.huluobo.a2109mvpimdemo.MainActivity;
import com.huluobo.a2109mvpimdemo.R;
import com.huluobo.a2109mvpimdemo.base.BaseActivity;
import com.huluobo.a2109mvpimdemo.register.RegisterActivity;
import com.huluobo.a2109mvpimdemo.utls.MD5Utils;
import com.huluobo.a2109mvpimdemo.utls.SPUtils;
import com.hyphenate.chat.EMClient;

public class LoginActivity extends BaseActivity<LoginContract.View, LoginPresenter> implements LoginContract.View {

    private EditText username, password;
    private Button login_btn;
    private TextView toRegister;

    @Override
    protected void initData() {
        presenter = new LoginPresenter();
    }

    @Override
    protected void initView() {
        TextView title = findViewById(R.id.header_title);
        title.setText("登录");
        username = findViewById(R.id.login_username);
        password = findViewById(R.id.login_password);
        login_btn = findViewById(R.id.login_btn);
        toRegister = findViewById(R.id.login_toRegister);
        login_btn.setOnClickListener(v -> {
            presenter.login(username.getText().toString(), password.getText().toString());
        });

        toRegister.setOnClickListener(v -> {
            Intent intent = new Intent(this, RegisterActivity.class);
            startActivity(intent);
        });
        if (SPUtils.getString(this, IMApp.SP_USERNAME, "").length() != 0) {
            username.setText(SPUtils.getString(this, IMApp.SP_USERNAME, ""));
        }

        if (SPUtils.getString(this, IMApp.SP_PASSWORD, "").length() != 0) {
            password.setText(SPUtils.getString(this, IMApp.SP_PASSWORD, ""));
        }
    }

    @Override
    protected int bindingLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void onUsernameError() {
        username.setError("用户名输入错误,需要首字符为英文,3-20位");
    }

    @Override
    public void onPasswordError() {
        password.setError("密码输入错误,需要3-20位数字");
    }

    @Override
    public void onStartLogin() {
        showProgressDialog("正在登录...");
    }

    @Override
    public void onLoginSuccess() {
        dismissProgressDialog();
        SPUtils.putString(this, IMApp.SP_USERNAME, username.getText().toString());
        SPUtils.putString(this, IMApp.SP_PASSWORD, password.getText().toString());
        String s = MD5Utils.encodeByMd5(username.getText().toString());
        Log.i("TagA", "s:" + s);
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void onLoginFailed(String error) {
        Log.i("TagA", "登录失败:" + error);
        dismissProgressDialog();
    }
}